package com.bignerdranch.android.expresshelper.Utils;

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.Map;

/**
 * Created by Administrator on 2016/6/12.
 */
public class RequestUtil {
    private static RequestQueue mRequestQueue;

    public static RequestQueue getRequestQueue(Context context) {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(context);
        }
        return mRequestQueue;
    }

    public static void execute(Context context, String url, Response.Listener listener, Response.ErrorListener errorListener) {

        getRequestQueue(context);

        StringRequest request = new StringRequest(url, listener, errorListener) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return super.getParams();
            }
        };
        //request.setTag();
        mRequestQueue.add(request);
    }

    public static void execute2(Context context, String url, Response.Listener listener, final Map<String, String> param) {

        getRequestQueue(context);

        StringRequest request = new StringRequest(Request.Method.POST, url, listener, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("RequestUtil", volleyError.getMessage() + "");
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return param;
            }
        };
        //request.setTag();
        mRequestQueue.add(request);
    }

    public static void executeJSONObject(Context context, String url, Response.Listener listener) {
        getRequestQueue(context);
        JsonObjectRequest request = new JsonObjectRequest(url, null, listener, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("RequestUtil", volleyError.getMessage() + "");
            }
        });
        mRequestQueue.add(request);
    }
    public static void executeJSONObject(Context context, String url, Response.Listener listener, Response.ErrorListener errorListener) {
        getRequestQueue(context);
        JsonObjectRequest request = new JsonObjectRequest(url, null, listener, errorListener);
        mRequestQueue.add(request);
    }

}
